<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<link href='fullcalendar.css' rel='stylesheet' />
<link href='fullcalendar.print.css' rel='stylesheet' media='print' />
<script src='lib/moment.min.js'></script>
<script src='lib/jquery.min.js'></script>
<script src='lib/jquery-ui.custom.min.js'></script>
<script src='fullcalendar.min.js'></script>
<script>
	var currentMousePos = {
    x: -1,
    y: -1
};
var popH ;
 var x;
 var y;
 var popX ,staPop=0;
$("#mess").hide();
$("#mess").css("display","none"); 
var startDate,endDate,allDay,timeText1,timeText2,ALLday,staEvent;
	//$(document).ready(function () {
	//
//});
	$(document).ready(function() {
		var liveDate = new Date(); // current Date
		$(document).on("mousemove", function (event) {
        currentMousePos.x = event.pageX;
        currentMousePos.y = event.pageY;
    });
	$('#my-next-button').click(function() {
    $(".messagepop").css("display","none");
});
	$(".bubbleclose").click(function(e){
	$(".messagepop").css("display","none");
	});
		$('#calendar').fullCalendar({
		header: {
				left: 'prev,next today',
				center: 'title',
				right: 'month,agendaWeek,agendaDay'
			},
			defaultDate: new Date(),
			 defaultDate: '2014-07-14',
		timezone: 'currentTimezone',
		timeFormat: 'H:mm ',
			events: {
            url: '/calendarGoogle/Calendar2.php',
            error: function () {
               // $('#script-warning').show();
            }
        },
			dayClick:function(date, jsEvent, view){
		$('.messagepop').css("display","none");
		$('.messagepop').css("display","inherit");
		$('#show').hide();
		$('#add').show();
		 var popH = $('.messagepop').outerHeight(true) + $('.arrow').outerHeight(true);
                var popX = $('.messagepop').outerWidth(true)/2;
               // $("#log1").text("pageX: " + x + ", pageY: " + y + " , popHeight:" + popH + " , popWidth:" + popX);
                $('.messagepop').css("top", (y - popH) + "px");
                $('.messagepop').css("left", (x -popX) + "px");
                $('.messagepop').css("display","inherit");
                $('.bgCalendar').css("display","inherit");
                $('.bgCalendar').css("z-index","950");
		},
		
		eventClick: function (event) {
                var popH = $('.messagepop').outerHeight(true) + $('.arrow').outerHeight(true);
			    addTitle();
            $("#message_submit").hide();
			$('#add').hide();
            $("#delEvent").show();
			$('#show').show();
                 $("#title").html(event.title);
            $("#detail").html(event.detail);
			var sendStart,sendEnd,changDay;
			if(event.start._i.substring(11,19)==""||event.end._i.substring(11,19)=="")
			{
				changDay=1;
				
			
			}else changDay=0;
            $("#startT").html(convertDate(event.start._i,event.end._i,changDay));
			//convertDate(event.start._i,event.end._i,changDay);
                var popH = $('.messagepop').outerHeight(true) + $('.arrow').outerHeight(true);
                var popX = $('.messagepop').outerWidth(true)/2;
               // $("#log1").text("pageX: " + x + ", pageY: " + y + " , popHeight:" + popH + " , popWidth:" + popX);
                $('.messagepop').css("top", (y - popH) + "px");
                $('.messagepop').css("left", (x -popX) + "px");
                $('.messagepop').css("display","inherit");
                $('.bgCalendar').css("display","inherit");
                $('.bgCalendar').css("z-index","950");
				
            staEvent = event;

        },
        loading: function (bool) {
		$(".messagepop").css("display","none");
            $('#loading').toggle(bool);
        },
		
		
		selectable: true,
			selectHelper: true,
			dragRevertDuration: 0,
		select: function (startDate, endDate, allDay, jsEvent) {

            // I use if because i dont want to add and event to any past dates
            if (liveDate > startDate) {
                alert('This date has been passed');
                return false;
            } else {
			//var timeFormat=startDate._d.substr(3, 20);
			var timeFormat=startDate._d;
			var t1=Date.parse(startDate._d);
			var t2=Date.parse(endDate._d);
			if(!isNaN(t2))
			{
			 timeText2=new Date(t2).toISOString();
			timeText2=timeText2.substr(0,19);
			timeText2=timeText2.replace("T"," ");
			allDay=false ;//"false";
			}
			else
			{
			timeText2='0000-00-00 00:00:00';
			allDay=true;//"true";
			}
			//var showText=t.toString().substr(0,20);
			//var showText=new Date(t).toString().substr(0,33);
			 timeText1=new Date(t1).toISOString();
			
			timeText1=timeText1.substr(0,19);
			
			timeText1=timeText1.replace("T"," ");
			
			var event = new Object();
			event.start = startDate;
			event.end = endDate;
			
			var ALLday=isOverlapping(event);
				if(ALLday)
				var title="";
				else
			//var title = prompt('New Charges:'+timeText1);
			addTitle2(startDate,endDate,allDay,timeText1,timeText2,ALLday);
			//$('.pop').slideFadeToggle();
			
			
			//var title = $( "#single" ).val();
			
			//add event
			
			
			
		//var title = prompt('New Charges:'+new Date(t));
	//	if (title) {
	//		$('#calendar').fullCalendar('renderEvent', {
    //                    title: title,
    //                    start: startDate,
    //                    end: endDate,
    //                    allDay: allDay
    //                }, false // make the event "unstick"
    //                );
    //                //var startDateString = $.fullCalendar.formatDate(startDate.start, 'yyyy-MM-dd HH:mm:ss');
    //                var startDateString =timeText1;
    //                var endDateString =timeText2;
    //                //var endDateString = $.fullCalendar.formatDate(endDate, 'yyyy-MM-dd');
	//				//var startDateString = '2014-07-05 09:30:00';
    //                //var endDateString = '2014-07-05 12:30:00';
    //                $.ajax({
    //                    type: 'post',
    //                    url: './new_events.php',
    //                    data: {
	//						action:"add",
    //                        startDate: startDateString,
    //                        endDate: endDateString,
    //                        eventTitle: title ,
	//						AllDay:ALLday
    //                    },
    //                    dateType: 'json',
    //                    success: function (resp) {
    //                      //events: "json.php" 
	//					  console.log("success return:", resp);
	//					  $('#calendar').fullCalendar('refetchEvents');
    //                    }
    //                });
    //            } // end of inner if
            } // end of else
           // $('#calendar').fullCalendar('select');
			//$('#calendar').fullCalendar( 'refetchEvents' );
        }
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		});
		
	});
	function isOverlapping(event){
    var array = $('#calendar').fullCalendar('clientEvents');
    for(i in array){
       // if(array[i].id != event.id){
       //     if(!(Date(array[i].start) >= Date(event.end) || Date(array[i].end) <= Date(event.start))){
       //         prompt('true');
       //     }
       // }
	   if ((event.end > array[i].start && event.start < array[i].end)||
	   (event.end>Date.parse(array[i].start2)&&event.start<Date.parse(array[i].end2))){
	   //prompt('true');
	   alert("กรุณาเลือกเวลาอีกครั้ง");
	   return true;
	   break;
	   }
    }
	//prompt('false');
	return false;
}
function addTitle2 (startDate,endDate,allDay,timeText1,timeText2,ALLday){
clearDt();
$('#startT2').val(timeText1);
$('#endT2').val(timeText2);
$('#mess').css("display","inherit"); 

}
function addTitle() {
    clearDt();
	$('#startT').val('');
	$('#endT').val('');
    $("#message_submit").show();
    $("#delEvent").hide();
	
    return false;

}

function clearDt() {
    $("#startT").val("");
    $("#endT").val("");
    $("#title").val("");
    $("#detail").val("")
    $("#title").prop('disabled', false);
    $("#startT").prop('disabled', false);
    $("#endT").prop('disabled', false);
    $("#detail").prop('disabled', false);
}

function deselect(e) {
    $('.pop').slideFadeToggle(function () {
        e.removeClass('selected');
    });
}
$(function () {
//convertDate();
   
});

$(document).on("mousemove", function (event) {
    
    x = event.pageX;
    y = event.pageY;
   
   // $("#log2").text("1pageX: " + x + ", pageY: " + y );
   
});
function convertDate(inputFormat1,inputFormat2,cheangDay) {
  function pad(s) { return (s < 10) ? '0' + s : s; }
  function timeFM(s) { return (s < 10) ? '0' + s : s; }
  function monthTx(d){ if(d.getMonth==0){
	monthTH="มกราคม";
	}else if(d.getMonth()==1){
	return "กุมภาพันธ์";
	}else if(d.getMonth()==2){
	return "มีนาคม";
	}else if(d.getMonth()==3){
	return "เมษายน";
	}else if(d.getMonth()==4){
	return "พฤษภาคม";
	}else if(d.getMonth()==5){
	return "มิถุนายน";
	}else if(d.getMonth()==6){
	return "กรกฎาคม";
	}else if(d.getMonth()==7){
	return "สิงหาคม";
	}else if(d.getMonth()==8){
	return "กันยายน";
	}else if(d.getMonth()==9){
	return "ตุลาคม";
	}else if(d.getMonth()==10){
	return "พฤศจิกายน";
	}else 
	return "ธันวาคม";}
  function yearTx(y){
			var yearTH=y.getFullYear()+543;
			return "พ.ศ."+yearTH;
			}
  function timeTx(t){
  var timeTH=timeFM(t.getHours())+":"+timeFM(t.getMinutes());
  return timeTH;
  }
  var monthTH,yearTH;
  inputFormat1=inputFormat1.replace(" ","T");
  inputFormat2=inputFormat2.replace(" ","T");
  var d1 = new Date(inputFormat1);
  
  var d2= new Date(inputFormat2);
  if(cheangDay==1)
  d2.setDate(d2.getDate()-1);
  var staTime;
	var Date1;
	if(d2=="")
	Date1=(""+Date1);
	else
	if(  d1.getDate()==d2.getDate()   &&  monthTx(d1)==monthTx(d2)  &&  yearTx(d2)==yearTx(d1))
	{
		Date1=d1.getDate()+" "+monthTx(d1)+" "+yearTx(d1);
		if(inputFormat1.length<=10)
		staTime=0;
	}	
	else if ( monthTx(d1)==monthTx(d2)  &&  yearTx(d2)==yearTx(d1))
	{	if(inputFormat1.length<=10){
		Date1=d1.getDate()+" - "+d2.getDate()+" "+monthTx(d1)+" "+yearTx(d1);
		staTime=0;
		}
		else
		{
		Date1=d1.getDate()+" "+monthTx(d1)+" "+yearTx(d1)+" เวลา "+timeTx(d1)+" น."+
		"<br> ถึง "+d2.getDate()+" "+monthTx(d2)+" "+yearTx(d2) +" เวลา "+timeTx(d2)+" น.";
		staTime=0;
		}
	}
	else
	{
	if(inputFormat1.length>10){
		Date1=d1.getDate()+" "+monthTx(d1)+" "+yearTx(d1)+" เวลา "+timeTx(d1)+" น."+
		"<br> ถึง "+d2.getDate()+" "+monthTx(d2)+" "+yearTx(d2) +" เวลา "+timeTx(d2)+" น.";
		staTime=0;
		}
		else 
		{
		Date1=d1.getDate()+" "+monthTx(d1)+" "+yearTx(d1)+
		"<br> ถึง "+d2.getDate()+" "+monthTx(d2)+" "+yearTx(d2);
		staTime=0;
		
		}
		
		
		
	}
	var Time;
	if(staTime!=0)
	Time="<br>เวลา "+timeTx(d1)+" - "+timeTx(d2)+" น.";
	else Time="";	 
	//$("#log3").text(Date1+" "+Time);
	return (""+Date1+Time);
}
$("#bubbleclose").click(function(e){
	$(".messagepop").css("display","none");
});
function close()
{
	$(".messagepop").css("display","none");
}
function sendMessage()
{
	$('#mess').css('display','none');
	var title = $( ".title" ).val();
	if (title) {
			$('#calendar').fullCalendar('renderEvent', {
                        title: title,
                        start: startDate,
                        end: endDate,
                        allDay: allDay
                    }, false // make the event "unstick"
                    );
                    //var startDateString = $.fullCalendar.formatDate(startDate.start, 'yyyy-MM-dd HH:mm:ss');
                    var startDateString =timeText1;
                    var endDateString =timeText2;
                    //var endDateString = $.fullCalendar.formatDate(endDate, 'yyyy-MM-dd');
					//var startDateString = '2014-07-05 09:30:00';
                    //var endDateString = '2014-07-05 12:30:00';
                    $.ajax({
                        type: 'post',
                        url: '/calendarGoogle/addCalendar.php',
                        data: {
							action:"add",
                            startDate: startDateString,
                            endDate: endDateString,
                            eventTitle: title ,
							AllDay:ALLday
                        },
                        dateType: 'json',
                        success: function (resp) {
    //                     events: {
    //       url: '/calendarGoogle/Calendar2.php',
    //       error: function () {
    //          // $('#script-warning').show();
    //       }
    //   },
						  console.log("success return:", resp);
						  $('#calendar').fullCalendar('refetchEvents');
                        }
                    });
                }
}
</script>
<style>

body {
		margin: 0;
		padding: 0;
		font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif;
		font-size: 14px;
	}

	#calendar {
	z-index=920;
		width: 700px;
		margin: 40px auto;
	}

div.calendar-trash{
float: left;
padding-right: 8px;
margin-right:5px;
padding-left:8px;
padding-top: 3px;
cursor: pointer;
}

.to-trash{
  background-color:#EAEAEA;
    -webkit-border-radius: 5em;
    border-radius: 5em;
}
a.selected {
  background-color:#1F75CC;
  z-index:100;
}


label {
  display: block;
  margin-bottom: 3px;
  padding-left: 15px;
  -indent: -15px;
}

.messagepop p, .messagepop.div {
 /* border-bottom: 1px solid #EFEFEF;*/
  margin: 8px 0;
  

}


label {
  display: block;
  margin-bottom: 3px;
  padding-left: 15px;
  -indent: -15px;
}

.messagepop p, .messagepop.div {
 /* border-bottom: 1px solid #EFEFEF;*/
  margin: 8px 0;
}
.arrow {
 width: 70px;
  height: 16px;
  overflow: hidden;
  position: absolute;
  left: 50%;
  margin-left: -35px;
  bottom: -16px;
}
.arrow:after {
content: "";
  position: absolute;
  left: 20px;
  top: -20px;
  width: 25px;
  height: 25px;
  -webkit-box-shadow: 6px 5px 9px -9px black,
                      5px 6px 9px -9px black;
  -moz-box-shadow: 6px 5px 9px -9px black,
                   5px 6px 9px -9px black;
  box-shadow: 6px 5px 9px -9px black,
              5px 6px 9px -9px black;
  -webkit-transform: rotate(45deg);
  -moz-transform:    rotate(45deg);
  -ms-transform:     rotate(45deg);
  -o-transform:      rotate(45deg);
}
.messagepop {
  background-color:#FFFFFF;
  border:1px solid #999999;
  cursor:default;
  z-align:left;
  height: auto;
width: 250px;
display:none;
z-index:950;
border-radius: 20px;
box-shadow: 0 0 3px rgb(194, 194, 194);
  opacity: 1;
  margin-top: 5px;
  -webkit-transition: all 0.2s ease;
  -moz-transition:    all 0.2s ease;
  -ms-transition:     all 0.2s ease;
  -o-transition:      all 0.2s ease;
position: absolute;
padding: 10px 20px;
margin-top: 20px;
}



.messagepop, .arrow:after {
background: white;
}
p#title {
color: blue;
font-weight: bold;
font-size: larger;
}
.bubbleclose {
background: url(//calendar.google.com/googlecalendar/images/combined_v46_vr.png) -228px -48px;
cursor: pointer;
height: 13px;
right: 16px;
top: 16px;
width: 13px;
position: absolute;
}
.bgCalendar{
z-index: 929;
/*background-color: rgb(243, 0, 0);*/
height: 100%;
width: 100%;
position:fixed;
top:0;
left:0;


}
p#startT{


font-size: 80%;
}
th#add {
    text-align: left;
    vertical-align:middle ;
    font-weight: lighter;
    font-size: small;
}
td#add{
    width:260px;
}
</style>
</head>
<body>

		<div id='script-warning'>
	</div>

	<div id='loading'>loading...</div>

	<div id='calendar'></div>
<div class="messagepop pop" id="mess"><div id="bubbleClose" class="bubbleclose" ></div>
  <form method="post" id="new_message" action="/messages">
   <div id="show">
	<p  id="title"></p>
	<p  id="startT"></p>
	<p  id="endT"></p>
	<p   id="detail"></p>
	</div>
	<div id="add">
	<table>
    <tr>
        <th class="add">งาน:</th>
        <td class="add">
            <input type="text" name="title" class="title" id="title" >
        </td>
    </tr>
	<tr>
            <th class="add">เริ่ม:</th>
        <td class="add">
            <input type="text" name="body" id="startT2" >
        </td>
    </tr>
        <tr>
            <th class="add">สิ้นสุด:</th>
        <td class="add">
            <input type="text" name="body" id="endT2" >
        </td>
    </tr>
    <tr>
        <th class="add">รายละเอียด:</th>
        <td class="add">
            <input type="text" name="firstname">
        </td>
    </tr>
	<tr>
        <td class="add"><input type="button" value="Send Message" name="commit" id="message_submit" onclick="sendMessage()"/></td>
        <td class="add">
            
        </td>
    </tr>
</table>
</div>
  </form>
  <div class="arrow"></div>
  
</div>

<div id="log1" ></div><br>
<div id="log2" ></div><br>
<div id="log3" ></div>

</body>
</html>
